#/bin/python
#-*- coding:utf-8 -*-

import os
import urllib
import urllib2

### djangoのバージョン変更
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from google.appengine.dist import use_library
use_library('django', '1.1')
import django

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.ext.db import djangoforms
from google.appengine.api import urlfetch
from google.appengine.api import users

### データモデル
class MessageStartEvent(db.Model):
    title = db.StringProperty(required=True, verbose_name=u"プロセス名称")
    url = db.URLProperty(required=True, verbose_name=u"ＵＲＩ")
    parameters = db.StringListProperty(verbose_name=u"パラメータ名")
    parameterNames = db.StringListProperty(verbose_name=u"フォームでの表示名")
    
    def parametersets(self):
        key_values = zip(self.parameters, self.parameterNames)
        key_values.sort()
        return key_values

class MessageStartEventForm(djangoforms.ModelForm):
    class Meta:
        model = MessageStartEvent

# 管理者向けページ
class SettingPage(webapp.RequestHandler):
    def get(self):
        mse_list = MessageStartEvent.all()
        
        form = MessageStartEventForm()
        render_html(self, 'qbpmsform_setting.html', {"mse_list": mse_list, "form": form})
    
    def post(self):
        form = MessageStartEventForm(self.request.POST)
        if form.is_valid():
            mse = form.save(commit=False)
            mse.put()
            self.redirect('/qbpmsform/admin/setting')
        else:
            self.response.out.write('ERROR')

class DeleteSettingPage(webapp.RequestHandler):
    def get(self):
        self.redirect('/qbpmsform/admin/setting')
    def post(self):
        key = self.request.get('key')
        mse = MessageStartEvent.get(key)
        if mse:
            mse.delete()
        self.redirect('/qbpmsform/admin/setting')

# エンドユーザ向けページ
class ShowFormPage(webapp.RequestHandler):
    def get(self):
        key = self.request.get('id')
        if key:
            mse = MessageStartEvent.get(key)
            formitems = []
            i = 0
            for param in mse.parameters:
                formitems.append({"label": mse.parameterNames[i], "name": param})
                i += 1
            
            render_html(self, 'qbpmsform_showform.html', {"mse": mse, "formitems": formitems})
        else:
            self.response.out.write('ERROR')
    def post(self):
        key = self.request.get('key')
        mse = MessageStartEvent.get(key)
        
        try:
            request_fields = {}
            for param in mse.parameters:
                req_value = self.request.get(param)
                request_fields[param] = req_value.encode('utf-8')
            payload = urllib.urlencode(request_fields)
            qbpms_response =urlfetch.fetch(
                url=mse.url,
                payload=payload,
                method=urlfetch.POST,
                headers={'Content-Type': 'application/x-www-form-urlencoded'}
            )
        except urlfetch.Error, e:
            self.response.out.write("ERROR:" + str(e))
        
        self.redirect('/qbpmsform/formend')

class FormEndPage(webapp.RequestHandler):
    def get(self):
        render_html(self, 'qbpmsform_formend.html')

class TopPage(webapp.RequestHandler):
    def get(self):
        mse_list = MessageStartEvent.all()
        render_html(self, 'qbpmsform_top.html', {"mse_list": mse_list})

### WEBページ描画用メソッド
def get_template_path(template_file_name):
    return os.path.join(os.path.dirname(__file__), 'templates', template_file_name)

def render_html(request_handler, template_file_name, parameters={}):
    user = users.get_current_user()
    parameters['user'] = user
    parameters['login_url'] = users.create_login_url(request_handler.request.url)
    parameters['logout_url'] = users.create_logout_url(request_handler.request.url)
    request_handler.response.out.write(
        template.render(get_template_path(template_file_name), parameters)
    )

application = webapp.WSGIApplication([
    ('/qbpmsform/admin/setting', SettingPage),
    ('/qbpmsform/admin/delete', DeleteSettingPage),
    ('/qbpmsform/show_form', ShowFormPage),
    ('/qbpmsform/formend', FormEndPage),
    ('/.*', TopPage)
], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()